//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js');
const api = require('../../utils/api.js');
Page({
    /**
     * 页面的初始数据
     */
    data: {
        page: 1,
        //banner数据
        bannerDatas: {},
        //热卖商品
        hotGoodList: {},
        //公告数据
        noticeDatas: {},
        //导航图标
        navigationDatas:{},
        //橱窗数据
        windowDatas:{},
        //秒杀产品
        spikeDatas: {},
        //套餐组合商品
        packageDatas:{},
        
        activityTitleDatas: {
            todayBuyingTitle: "今日限时抢购",
            packageTitle: "套餐优惠专区"
        },
        //页面颜色
        pageColor: app.pageColor,

        //轮播图配置
        bannerConfiguration: app.bannerConfiguration

    },

    /**
     * 页面跳转
     */

    navigateTo: function (url) {
        wx.navigateTo({
            url: url
        })
    },

    //商品点击事件
    onTapGoods: function (res) {
        var goodId = res.currentTarget.dataset.goodid;
        this.toGoodDetail(goodId);
    
    },
    /**
     * 进入商品详情页
     */

    toGoodDetail: function (goodId){
        this.navigateTo("../goodDetail/goodDetail?goodId=" + goodId)
    },

    /**
     * 获取热卖推荐商品回调
     */
    HotGoodListCallBack: function (res) {
        for (var i = 0; i < res.goods.data.length; i++) {
            if (res.goods.data[i].name.length > 25) {
                res.goods.data[i].name = res.goods.data[i].name.substring(0, 25) + "..."
            }
        }
        this.setData({
            hotGoodList: res
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
       
    },
    search: function () {
        wx.navigateTo({
            url: '../search/search'
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        util.setNavigationBarTitle("首页");
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let [urlBanner, urlNotice, urlNavigation, urlWindow, urlSpike, urlComposer, urlHotGoods] = [api.banner(), api.Notice(), api.Navigation(), api.Window(), api.Spike(), api.Composer(), api.HotGoods()];
        //获取banner
        util.http(false, "GET", urlBanner, {}, this.bannerSuccessCallBack);

        //获取公告
        util.http(false, "GET", urlNotice, {}, this.noticeSuccessCallBack);

        //获取导航
        util.http(false, "GET", urlNavigation, {}, this.navigationSuccessCallBack);

        //获取首页橱窗
        util.http(false, "GET", urlWindow, {}, this.windowSuccessCallBack);

        //获取限时抢购商品
        util.http(false, "GET", urlSpike, {}, this.spikeSuccessCallBack);

        //获取套餐商品
        util.http(false, "GET", urlComposer, {}, this.packageSuccessCallBack);

        
        //获取热卖推荐商品
        util.http(false, "GET", urlHotGoods, { page: this.data.page }, this.HotGoodListCallBack) 
        
    },
    /**
     * 获取banner回调
     */
    bannerSuccessCallBack: function (res) {
        this.setData({
            bannerDatas: res
        })
    },
    /**
     * 获取公告回调
     */
    noticeSuccessCallBack: function (res) {
        this.setData({
            noticeDatas: res
        })
       
    },

    /**
     * 获取公告回调
     */
    navigationSuccessCallBack: function (res) {
        this.setData({
            navigationDatas: res
        })

    },

    /**
     * 获取橱窗回调
     */
    windowSuccessCallBack: function (res) {
        for (var i = 0; i < res.windows.length;i++){
            res.windows[i].title = res.windows[i].title.length >= 7 ? res.windows[i].title.substring(0, 7) + "..." : res.windows[i].title
            res.windows[i].des = res.windows[i].des.length >= 7 ? res.windows[i].des.substring(0, 7) + "..." : res.windows[i].des
        }
        this.setData({
            windowDatas: res
        })

    },

    /**
     * 获取秒杀产品回调
     */
    spikeSuccessCallBack: function (res) {
        for (var i = 0; i < res.good_detail.length; i++) {
            res.good_detail[i].name = res.good_detail[i].name.length >= 9 ? res.good_detail[i].name.substring(0, 9) + "..." : res.good_detail[i].name;           
        }
        var myDate = new Date();//获取系统当前时间
        res.currentTimestamp = myDate.getTime();
        res.title = "今日限时抢购"
        //开抢中
        if (res.currentTimestamp >= res.start_at * 1000 && 
            res.currentTimestamp <= res.end_at * 1000)
        {
            res.text="开抢中"
            res.state = 1;
        } else if (res.currentTimestamp < res.start_at * 1000){
            res.text = "即将开抢"
            res.state = 2;
        } else if (res.currentTimestamp > res.end_at * 1000){
            res.text = "已结束"
            res.state = 3;
        }
        var startAtDate = new Date(res.start_at*1000)
        var endAtDate = new Date(res.end_at * 1000)
        res.start_at = util.formatTime(startAtDate)
        res.end_at = util.formatTime(endAtDate)
        this.setData({
            spikeDatas: res,
        })
    },

    /**
     * 获取套餐优惠产品回调
     */
    packageSuccessCallBack: function (res) {
        for (var i = 0; i < res.composers.length; i++) {
            for (var j = 0; j < res.composers[i].goodDetail.length; j++) {
                res.composers[i].goodDetail[j].name = res.composers[i].goodDetail[j].name.length >= 9 ? res.composers[i].goodDetail[j].name.substring(0, 9) + "..." : res.composers[i].goodDetail[j].name;
            }
        }

        for (var i = 0; i < res.composers.length; i++) {
            var oldPrice = 0;
            for (var j = 0; j < res.composers[i].goodDetail.length; j++) {
                res.composers[i].goodDetail[j].name = res.composers[i].goodDetail[j].name.length >= 9 ? res.composers[i].goodDetail[j].name.substring(0, 9) + "..." : res.composers[i].goodDetail[j].name;
                oldPrice += parseInt(res.composers[i].goodDetail[j].price)
            }
            res.composers[i].oldPrice = oldPrice;
        }
        res.title = "套餐优惠专区"

        this.setData({
            packageDatas: res,
        })
    },


     /**
   * 是否库存充足
   */
  hasStock:function (stock) {
    if(stock<=0){
        util.failToast("库存不足");
        return false;
    }
    return true;
  },

  /**
   * 获取商品信息
   */
  getGoodInfo:function(position){
    var packageGood = this.data.packageDatas.composers[position];
    //存入对象
    var selectGoodInfo={};
    selectGoodInfo.goodId = packageGood.id;
    selectGoodInfo.goodName=packageGood.name.length>25?packageGood.name.substring(0,25)+"...":packageGood.name;
    selectGoodInfo.goodPrice = packageGood.price;
    selectGoodInfo.goodOldPrice = packageGood.price;
    selectGoodInfo.goodDes = "";
    selectGoodInfo.goodStock = packageGood.stock;
    selectGoodInfo.goodCover = packageGood.cover;
    selectGoodInfo.goodCount = 1;
    selectGoodInfo.skuName = "";
    selectGoodInfo.goodSales = packageGood.sales;
    selectGoodInfo.skuId = "";
    selectGoodInfo.state = 0;
    return selectGoodInfo;
  },

  /**
   * 添加购物车
   */
  addShop:function (options) {
    var position = options.currentTarget.dataset.position;
    var packageGood = this.data.packageDatas.composers[position];
    if(this.hasStock(packageGood.stock)){
        var goodInfo = this.getGoodInfo(position);
        var selectGoodInfoArr = util.getStorage("selectGoodInfoArr")==""?[]:util.getStorage("selectGoodInfoArr")
        var count =1;
        for (var i = 0; i < selectGoodInfoArr.length;i++){
            if (goodInfo.goodId == selectGoodInfoArr[i].goodId){
                selectGoodInfoArr[i].goodCount +=1 ;
                count = 2;
                break;
            }
        }
        if (count ==1){
            selectGoodInfoArr.push(goodInfo);
        }
        util.setStorage("selectGoodInfoArr", selectGoodInfoArr);
        util.successToast("加入购物车成功") 
    }

    
  },


  //立即购买
  buy: function (options) {
    var position = options.currentTarget.dataset.position;
    var packageGood = this.data.packageDatas.composers[position];
    var goodInfoArr=[]
    if(this.hasStock(packageGood.stock)){
        var goodInfo = this.getGoodInfo(position);
        goodInfoArr.push(goodInfo)
        this.navigateTo("../firmOrder/firmOrder?goodInfoArr=" + JSON.stringify(goodInfoArr))
    
    }
    
},

    /**
     * 抢购商品
     */
    onTap:function(e){
        var state = e.currentTarget.dataset.state;
        if(state==2){
            util.failToast("抢购即将开启！");
            return;
        }
        if(state==3){
            util.failToast("抢购已结束！");
            return;
        }
        var id = e.currentTarget.dataset.id;
        this.toGoodDetail(id)

        
        

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
